<template>
  <div>
    <SearchForm
      @search="onSearch"
      @reset="onReset"
      :search-list="searchList" 
      :search-params="searchParams">
    </SearchForm>

    <div class="table-layout">
      <el-card shadow="never">
        <div class="table-handle">
          <el-button type="primary" size="mini" icon="el-icon-download" @click="handleExport">导出</el-button>
        </div>
        <div class="table-box">
          <el-table
            size="large"
            stripe
            border
            v-loading="loading"
            max-height="500px"
            :data="tableData"
            row-key="id"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.8)"
          >
            <el-table-column align="center" label="ID" width="80" prop="id" />
            <el-table-column align="center" label="用户" width="120">
              <template slot-scope="{row}">
                <span>{{ row.user ? row.user.name : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="图书馆" width="120">
              <template slot-scope="{row}">
                <span>{{ row.library ? row.library.name : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="楼层" width="100">
              <template slot-scope="{row}">
                <span>{{ row.floor ? row.floor.floor_number : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="区域" width="100">
              <template slot-scope="{row}">
                <span>{{ row.area ? row.area.name : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="座位" width="100">
              <template slot-scope="{row}">
                <span>{{ row.seat ? row.seat.name : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="预约时间" width="180">
              <template slot-scope="{row}">
                <span>{{ row.start_time }} - {{ row.end_time }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="状态" width="100">
              <template slot-scope="{row}">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间" width="180" prop="create_time" />
            <el-table-column align="center" label="操作" width="150" fixed="right">
              <template slot-scope="{row}">
                <el-button size="mini" type="text" @click="handleDetail(row)">详情</el-button>
                <el-button 
                  v-if="row.status === 'pending' || row.status === 'confirmed'" 
                  size="mini" 
                  type="text" 
                  style="color: #F56C6C"
                  @click="handleCancel(row)">取消</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      <div class="page-box">
        <el-pagination
          background
          :current-page="pageNo"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize"
          @size-change="changePageSize"
          @current-change="changePageNo"
        />
      </div>
    </div>

    <el-dialog title="预约详情" :visible.sync="detailDialogVisible" width="600px">
      <div v-if="detailData" class="detail-container">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="预约ID">{{ detailData.id }}</el-descriptions-item>
          <el-descriptions-item label="预约状态">
            <el-tag :type="getStatusType(detailData.status)">
              {{ getStatusText(detailData.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户">{{ detailData.user ? detailData.user.name : '-' }}</el-descriptions-item>
          <el-descriptions-item label="联系方式">{{ detailData.user ? detailData.user.phone : '-' }}</el-descriptions-item>
          <el-descriptions-item label="图书馆">{{ detailData.library ? detailData.library.name : '-' }}</el-descriptions-item>
          <el-descriptions-item label="楼层">{{ detailData.floor ? detailData.floor.floor_number : '-' }}</el-descriptions-item>
          <el-descriptions-item label="区域">{{ detailData.area ? detailData.area.name : '-' }}</el-descriptions-item>
          <el-descriptions-item label="座位">{{ detailData.seat ? detailData.seat.name : '-' }}</el-descriptions-item>
          <el-descriptions-item label="预约时间段" :span="2">{{ detailData.start_time }} - {{ detailData.end_time }}</el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ detailData.create_time }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ detailData.remark || '-' }}</el-descriptions-item>
        </el-descriptions>
        
        <div v-if="detailData.logs && detailData.logs.length > 0" class="logs-container">
          <div class="logs-title">操作日志</div>
          <el-timeline>
            <el-timeline-item
              v-for="(log, index) in detailData.logs"
              :key="index"
              :icon="getLogTypeIcon(log.action)"
              :type="log.action === 'cancel' ? 'danger' : 'primary'"
              :timestamp="log.create_time"
            >
              {{ getLogActionText(log.action) }}
              <div v-if="log.remark" class="log-remark">备注: {{ log.remark }}</div>
            </el-timeline-item>
          </el-timeline>
        </div>
        
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            v-if="detailData.status === 'pending' || detailData.status === 'confirmed'" 
            type="danger" 
            @click="handleCancelFromDetail">取消预约</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crud from "@/mixins/crud";
import { http } from '@/api'
import SearchForm from "@/components/SearchForm"

export default {
  name: 'ReservationRecords',
  components: {
    SearchForm
  },
  mixins: [crud],
  data() {
    return {
      request: http.reservations,
      tableData: [],
      loading: false,
      pageNo: 1,
      pageSize: 10,
      pageSizes: [10, 20, 30, 40, 50],
      totalSize: 0,
      searchParams: {
        library_id: undefined,
        floor_id: undefined,
        area_id: undefined,
        seat_name: '',
        user_name: '',
        status: undefined,
        date_range: []
      },
      defaultParams: {},
      searchList: [
        {
          label: '图书馆',
          prop: 'library_id',
          name: 'select',
          clearable: true,
          options: [],
          change: (val) => this.handleLibraryChange(val)
        },
        {
          label: '楼层',
          prop: 'floor_id',
          name: 'select',
          clearable: true,
          options: [],
          change: (val) => this.handleFloorChange(val)
        },
        {
          label: '区域',
          prop: 'area_id',
          name: 'select',
          clearable: true,
          options: []
        },
        {
          label: '座位名称',
          prop: 'seat_name',
          name: 'input',
          clearable: true
        },
        {
          label: '用户名称',
          prop: 'user_name',
          name: 'input',
          clearable: true
        },
        {
          label: '状态',
          prop: 'status',
          name: 'select',
          clearable: true,
          options: [
            { label: '待确认', value: 'pending' },
            { label: '已确认', value: 'confirmed' },
            { label: '已完成', value: 'completed' },
            { label: '已取消', value: 'cancelled' },
            { label: '已过期', value: 'expired' }
          ]
        },
        {
          label: '预约日期',
          prop: 'date_range',
          name: 'daterange',
          clearable: true,
          change: (val) => this.handleDateRangeChange(val)
        }
      ],
      libraryOptions: [],
      floorOptions: [],
      areaOptions: [],
      detailDialogVisible: false,
      detailData: null
    }
  },
  created() {
    this.getLibraryOptions();
  },
  methods: {
    formatTableData(tableData) {
      // 可以在这里对表格数据进行处理
    },
    getQueryParams() {
      const params = {
        pageNum: this.pageNo,
        pageSize: this.pageSize,
        ...this.defaultParams
      }
      
      if (this.searchParams.library_id) {
        params.library_id = this.searchParams.library_id
      }
      
      if (this.searchParams.floor_id) {
        params.floor_id = this.searchParams.floor_id
      }
      
      if (this.searchParams.area_id) {
        params.area_id = this.searchParams.area_id
      }
      
      if (this.searchParams.seat_name) {
        params.seat_name = this.searchParams.seat_name
      }
      
      if (this.searchParams.user_name) {
        params.user_name = this.searchParams.user_name
      }
      
      if (this.searchParams.status) {
        params.status = this.searchParams.status
      }
      
      if (this.searchParams.date_range && this.searchParams.date_range.length === 2) {
        params.start_date = this.searchParams.date_range[0]
        params.end_date = this.searchParams.date_range[1]
      }
      
      return params
    },
    getLibraryOptions() {
      http.libraries.list().then(response => {
        this.libraryOptions = response.data;
        const librarySelectIndex = this.searchList.findIndex(item => item.prop === 'library_id');
        if (librarySelectIndex !== -1) {
          this.searchList[librarySelectIndex].options = this.libraryOptions.map(item => {
            return { label: item.name, value: item.id };
          });
        }
      });
    },
    getFloorOptions(libraryId) {
      this.floorOptions = [];
      this.searchParams.floor_id = undefined;
      this.areaOptions = [];
      this.searchParams.area_id = undefined;
      
      if (libraryId) {
        http.libraryFloors.list({ library_id: libraryId }).then(response => {
          this.floorOptions = response.data;
          const floorSelectIndex = this.searchList.findIndex(item => item.prop === 'floor_id');
          if (floorSelectIndex !== -1) {
            this.searchList[floorSelectIndex].options = this.floorOptions.map(item => {
              return { label: `${item.floor_number}楼`, value: item.id };
            });
          }
        });
      }
    },
    getAreaOptions(floorId) {
      this.areaOptions = [];
      this.searchParams.area_id = undefined;
      
      if (floorId) {
        http.libraryAreas.list({ floor_id: floorId }).then(response => {
          this.areaOptions = response.data;
          const areaSelectIndex = this.searchList.findIndex(item => item.prop === 'area_id');
          if (areaSelectIndex !== -1) {
            this.searchList[areaSelectIndex].options = this.areaOptions.map(item => {
              return { label: item.name, value: item.id };
            });
          }
        });
      }
    },
    handleLibraryChange(val) {
      if (val) {
        this.getFloorOptions(val);
      } else {
        this.floorOptions = [];
        this.searchParams.floor_id = undefined;
        this.areaOptions = [];
        this.searchParams.area_id = undefined;
      }
    },
    handleFloorChange(val) {
      if (val) {
        this.getAreaOptions(val);
      } else {
        this.areaOptions = [];
        this.searchParams.area_id = undefined;
      }
    },
    handleDateRangeChange(val) {
      this.searchParams.date_range = val;
    },
    getStatusType(status) {
      switch (status) {
        case 'pending':
          return 'warning';
        case 'confirmed':
          return 'success';
        case 'completed':
          return 'success';
        case 'cancelled':
          return 'danger';
        case 'expired':
          return 'info';
        default:
          return 'info';
      }
    },
    getStatusText(status) {
      switch (status) {
        case 'pending':
          return '待确认';
        case 'confirmed':
          return '已确认';
        case 'completed':
          return '已完成';
        case 'cancelled':
          return '已取消';
        case 'expired':
          return '已过期';
        default:
          return '未知';
      }
    },
    getLogTypeIcon(action) {
      switch (action) {
        case 'create':
          return 'el-icon-plus';
        case 'confirm':
          return 'el-icon-check';
        case 'complete':
          return 'el-icon-success';
        case 'cancel':
          return 'el-icon-close';
        case 'expire':
          return 'el-icon-time';
        default:
          return 'el-icon-info';
      }
    },
    getLogActionText(action) {
      switch (action) {
        case 'create':
          return '创建预约';
        case 'confirm':
          return '确认预约';
        case 'complete':
          return '完成预约';
        case 'cancel':
          return '取消预约';
        case 'expire':
          return '预约过期';
        default:
          return '未知操作';
      }
    },
    handleDetail(row) {
      http.reservations.detail(row.id).then(response => {
        this.detailData = response.data;
        this.detailDialogVisible = true;
      });
    },
    handleCancel(row) {
      this.$confirm('确认取消该预约？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.reservations.cancel(row.id).then(() => {
          this.$message.success('预约已取消');
          this.onSearch();
        });
      }).catch(() => {
        // 取消操作
      });
    },
    handleCancelFromDetail() {
      this.$confirm('确认取消该预约？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.reservations.cancel(this.detailData.id).then(() => {
          this.$message.success('预约已取消');
          this.detailDialogVisible = false;
          this.onSearch();
        });
      }).catch(() => {
        // 取消操作
      });
    },
    handleExport() {
      this.$confirm('确认导出所有预约记录？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.downloadLoading = true;
        const params = this.getQueryParams();
        delete params.pageNum;
        delete params.pageSize;
        
        http.reservations.export(params).then(response => {
          this.downloadLoading = false;
          const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = '预约记录.xlsx';
          link.click();
        }).catch(() => {
          this.downloadLoading = false;
        });
      });
    }
  }
}
</script>

<style scoped lang="scss">
.table-layout {
  margin-top: 20px;
}

.table-handle {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.table-box {
  margin-bottom: 20px;
}

.page-box {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.detail-container {
  padding: 20px;
}

.logs-container {
  margin-top: 30px;
}

.logs-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.log-remark {
  color: #909399;
  font-size: 13px;
  margin-top: 5px;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style>
